﻿using HelenServer.BugEngine.Contracts;
using HelenServer.Grpc.Contracts;
using HelenServer.Migrator;

namespace HelenServer.BugEngine.Services;

[Injection(typeof(IMigrateService))]
internal class MigrateService : IMigrateService
{
    private readonly IDalMigrateService _service;
    private readonly IGrpcClientFactory _factory;
    private readonly ILogger<MigrateService> _logger;

    private readonly ZentaoDbOptions _options;

    public MigrateService(IDalMigrateService service, IGrpcClientFactory factory, ILogger<MigrateService> logger, IOptions<ZentaoDbOptions> options)
    {
        _service = service;
        _factory = factory;
        _logger = logger;
        _options = options.Value;
    }

    public async Task<OperationResult<bool>> MigrateAsync(CancellationToken cancellationToken = default)
    {
        MigrateProvider.ReadyToMigrate(new ZentaoDbOptions
        {
            IP = _options.IP,
            DbPort = _options.DbPort,
            DbUser = _options.DbUser,
            DbPassword = _options.DbPassword,
        });

        Helen.Metadata.TryAdd("zt_ip", _options.IP);
        Helen.Metadata.TryAdd("zt_port", _options.Port.ToString());
        Helen.Metadata.TryAdd("zt_authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_options.ClientId}:{_options.Secret}"))}");

        var ucMetadata = new Metadata
        {
            { "zt_ip", _options.IP },
            { "zt_dbport", _options.DbPort },
            { "zt_user", _options.DbUser },
            { "zt_pwd", _options.DbPassword }
        };

        #region UserCenter迁移
        var uc = _factory.GetService<IUCMigrateSingal, byte, GrpcResult<bool>>("uc");
        //var ucGrpcResult = await uc.InvokeAsync(1, ucMetadata, cancellationToken);
        #endregion

        //if (!ucGrpcResult.Data)
        //{
        //    return OperationResult<bool>.Failed(ucGrpcResult.Message);
        //}

        //_logger.LogInformation("已完成 UserCenter 的迁移");

        var bgeResult = await _service.MigrateAsync(cancellationToken);

        await MigrateProvider.EndMigrationAsync();

        return bgeResult;
    }
}